<?php
declare(strict_types=1);

namespace Modules\Grade\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Modules\Grade\Models\Grade;
use Illuminate\Http\Request;
use Modules\Grade\Providers\GradeServiceProvider;
use Modules\Subject\Models\Subject;


class GradeController extends Controller
{
    public function __construct(
        protected readonly Grade $model
    ){}

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        $subjects  = Subject::query()->select(['id','name','grade_id'])->get();
        $subjects  = $this->getKeyArray($subjects, "grade_id");
        $gradeList = Grade::query()->where('status' ,1)->select(['id','name'])->get();

        foreach ($gradeList as &$gradeItem)
        {
            $gradeId = $gradeItem['id'];
            if (isset($subjects[$gradeId]))
            {
                $gradeItem['subject'] = $subjects[$gradeId];
            }
        }

        return $gradeList;
    }

    public function add(Request $request)
    {
        $data  = [];
        $param = $request->all();

        if (isset($param['name']))
        {
            $data['name'] = $param['name'];
        }

        return $this->model->createBy($data);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function delete(Request $request)
    {
        $id = $request->get("id");

        if ($id)
        {
            $data['status'] = 2;
            return $this->model->updateBy($id, $data);
        }

        throw new FailedException("删除失败");
    }

    /**
     * @param $array
     * @param $filed
     * @return array
     */
    protected function getKeyArray($array = [], $filed = ""): array
    {
        $result = [];

        foreach ($array as $item)
        {
            $result[$item[$filed]][] = [
                "id" => $item['id'],
                'name' => $item['name']
            ];
        }

        return $result;
    }
}
